package org.tea.inventory.db.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.tea.inventory.db.dao.AlumniFriUserMapper;
import org.tea.inventory.db.dao.AlumniUserMapper;
import org.tea.inventory.db.dao.AlumniUserMessageMapper;
import org.tea.inventory.db.dao.ApproveHistoryMapper;
import org.tea.inventory.db.domain.AlumniFriUser;
import org.tea.inventory.db.domain.AlumniUser;
import org.tea.inventory.db.domain.AlumniUserMessage;
import org.tea.inventory.db.domain.ApproveHistory;
import org.tea.inventory.db.util.CommonUtil;
import org.tea.inventory.db.util.PYIndexStrUtil;
import org.tea.inventory.db.util.wx.WeixinUtil;
import org.tea.inventory.db.util.wx.entity.AccessToken;
import org.tea.inventory.db.util.wx.entity.MessageData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
	@Resource
	private AlumniUserMapper alumniUserMapper;

	@Resource
	private AlumniFriUserMapper alumniFriUserMapper;

	@Resource
	private AlumniUserMessageMapper alumniUserMessageMapper;
	@Resource
	private ApproveHistoryMapper approveHistoryMapper;

	/**
	 * 查询校友录列表,待审核中的用户除外
	 * @param alumniUser
	 * @param page
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> queryAlumniUser(AlumniUser alumniUser, Integer page, Integer limit,
												String sort, String order) {
		PageHelper.startPage(page, limit);
		List<AlumniUser> list = alumniUserMapper.selectAlumniUser(alumniUser);
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/**
	 * 查询游客数量，待审核中的用户除外
	 * @param page
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> queryAlumniUserNotYK(Integer page, Integer limit,
													 String sort, String order){
		PageHelper.startPage(page, limit);
		List<AlumniUser> list = alumniUserMapper.selectAlumniUserNotYK();
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}



	/**
	 * 查询待审核用户列表
	 * @param page
	 * @param size
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> querySelective(AlumniUser example, 
			Integer page, Integer size, String sort, String order) {

		PageHelper.startPage(page, size);
		List<AlumniUser> list = alumniUserMapper.selectByExample(example);
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/**
	 * 批量审核成员
	 * @param ids
	 * @return
	 */
	public Map<String, Object> passAudit(Integer adminId,
										 Integer auditStatus,
										 String reason,
										 String[] ids) {
		Map<String,Object> map = new HashMap<String,Object>();
		for (String id : ids) {
			AlumniUser user = alumniUserMapper.selectByPrimaryKey(Integer.valueOf(id));
			if(user != null && user.getAuditStatus() == 1) {
                //发送系统消息通知用户
                String content = "";
                String result = "";
                if(auditStatus == 3) {
                    result = "通过";
                    content = "恭喜你通过通誉审核认证";
                } else {
                    result = "驳回";
                    String re = "";
                    if(!StringUtils.isEmpty(reason))
                        re="驳回原因："+reason;
                    content = "sorry,您的资料审核未通过。"+re;

                    //插入驳回历史
                    insertApproveHistory(adminId ,re, user);
                }
                sendMessage(user.getId()+"", "system", content, null);

                //发送微信通知
                MessageData msgData = new MessageData();
                msgData.setKeyword1(user.getUserName());
                msgData.setKeyword2("通誉审核认证");
                msgData.setKeyword3(result);
                msgData.setKeyword4(content);
                sendWXMSG(user.getId(), msgData);

                //更新用户状态
				user.setAuditStatus(auditStatus);
				user.setAuditDataTime(new Date());
				user.setBeginDate(null);
				user.setLastLoginTime(null);
				if(auditStatus == 2) {
					user.setReason(reason);
					user.setTemRoleType(user.getRoleType());
				} else {
					user.setRoleType(user.getTemRoleType());
					user.setReason("");
				}
				alumniUserMapper.updateByPrimaryKeySelective(user);
			}
		}
		map.put("state", "success");
		map.put("massege", "审核成功 ");
		return map;
	}

	/**
	 * 审核
	 * @param alumniUser
	 * @return
	 */
	public Map<String, Object> auditUser(Integer adminId, AlumniUser alumniUser) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(alumniUser.getId());
		if(user != null && user.getAuditStatus() == 1) {
			Integer auditStatus = alumniUser.getAuditStatus();
			String reason = alumniUser.getReason();
            //发送系统消息通知用户
            String content = "";
            String result = "";
            if(auditStatus == 3) {
                result = "通过";
                content = "恭喜你通过通誉审核认证";
            } else {
                result = "驳回";
                String re = "";
                if(!StringUtils.isEmpty(reason))
                    re="驳回原因："+reason;
                content = "sorry,您的资料审核未通过。"+re;

                //插入驳回历史
                insertApproveHistory(adminId ,re, user);
            }
            sendMessage(user.getId()+"", "system", content, null);

            //发送微信通知
            MessageData msgData = new MessageData();
            msgData.setKeyword1(user.getUserName());
            msgData.setKeyword2("通誉审核认证");
            msgData.setKeyword3(result);
            msgData.setKeyword4(content);
            sendWXMSG(user.getId(), msgData);

            //更新用户状态
			user.setAuditStatus(auditStatus);
			user.setAuditDataTime(new Date());
			user.setBeginDate(null);
			user.setLastLoginTime(null);
			if(auditStatus == 2) {
				user.setReason(reason);
				user.setTemRoleType(user.getRoleType());
			} else {
				user.setRoleType(user.getTemRoleType());
				user.setReason("");
			}
			alumniUserMapper.updateByPrimaryKeySelective(user);


			resultMap.put("state", "success");
			resultMap.put("massege", "审核成功");
		} else {
			resultMap.put("state", "failuren");
			resultMap.put("massege", "用户不存在");
		}
		return resultMap;

	}
	
	/**
	 * 根据主键id查询用户
	 * @param userId
	 * @return
	 */
	public AlumniUser findById(Integer userId) {
		return alumniUserMapper.selectByPrimaryKey(userId);
	}

	public Map findAlumniUserByUserId(Integer userId) {
		return alumniUserMapper.selectById(userId);
	}
	/**
	 * 查询用户数量
	 * @return
	 */
	public int count(AlumniUser user) {
		return (int)alumniUserMapper.countByUser(user);
	}
	/**
	 * 根据openId查询用户
	 * @param openId
	 * @return
	 */
	public AlumniUser queryByOid(String openId) {

		return alumniUserMapper.selectOneByOpenId(openId);
	}
	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(AlumniUser user) {
		AlumniUser alumniUser = alumniUserMapper.selectOneByOpenId(user.getOpenId());
		if(alumniUser == null)
			alumniUserMapper.insertSelective(user);
	}
	/**
	 * 修改用户
	 * @param user
	 */
	public void updateUser(AlumniUser user) {
		alumniUserMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 修改用户微信名称
	 * @param wechatName
	 * @return
	 */
	public int updateWechatName(String wechatName,String openId){
		return alumniUserMapper.updateWechatName(wechatName,openId);
	}

	/**
	 * 查询我关注的用户
	 * @param userId
	 * @return
	 */
	public Map<String, Object> findUserConcernedByUserId(Integer userId, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniFriUserMapper.selectUserByFKUserId(userId);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("pageNum",pageinfo.getPageNum());
		resMap.put("pageSize", pageinfo.getPageSize());
		resMap.put("startRow", pageinfo.getStartRow());
		resMap.put("endRow", pageinfo.getEndRow());
		resMap.put("total", pageinfo.getTotal());
		resMap.put("pages", pageinfo.getPages());

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 搜索我关注的用户
	 * @param userId
	 * @param valString
	 * @return
	 */
	public Map<String, Object> findUserConcerned(Integer userId, String valString) {
		List<Map> list = alumniFriUserMapper.selectUserConcerned(userId, valString);
		Map<String,Object> resMap = new HashMap<String,Object>();

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 查询校友录列表
	 * @param page
	 * @param size
	 * @return
	 */
	public Map<String, Object> findAlumniRecordById(Integer userId, Integer page, Integer size) {
		List<Map> list = alumniUserMapper.findAlumniRecordById(userId, (page - 1) * size, size);
		int total = alumniUserMapper.selectTotalCount(userId);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("page",page);
		resMap.put("pageSize", size);
		resMap.put("total", total);

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 添加关注用户记录
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> alreadyFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null && user.getAuditStatus() == 3) {
			AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
			if(afriUser == null) {
				afriUser = new AlumniFriUser();
				afriUser.setFkUserId(userId);
				afriUser.setFriUserId(friUserId);
				afriUser.setCreateDate(new Date());
				alumniFriUserMapper.insertSelective(afriUser);
				result.put("state", "success");
				result.put("massege", "关注成功");
			} else {
				result.put("state", "failuren");
				result.put("massege", "已关注");
			}
		} else {
			result.put("state", "failuren");
			result.put("massege", "您的身份目前待验证");
		}
		return result;
	}
	
	/**
	 * 查询是否关注
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> checkFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
		if(afriUser == null) {
			result.put("isFollowed", false);
		} else {
			result.put("isFollowed", true);
		}
		return result;
	}

	/**
	 * 按条件查询校友录
	 * @param userId
	 * @param valString
	 * @return
	 */
	public Map<String, Object> findAlumniRecord(Integer userId, String valString) {
		List<Map> list = alumniUserMapper.findAlumniRecord(userId, valString);
		Map<String,Object> resMap = new HashMap<String,Object>();
		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 提交待审核认证
	 * @param userId
	 * @return
	 */
	public Map<String, Object> submitAudit(Integer userId, String formId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String temRoleType = user.getTemRoleType();
			if(StringUtils.isNotBlank(temRoleType)){
				if("通誉伙伴".equals(temRoleType)) {
					user.setAuditStatus(3);
					user.setRoleType(temRoleType);
					alumniUserMapper.updateByPrimaryKeySelective(user);
					result.put("state", "success");
					result.put("massege", "提交成功");
				} else if("游客".equals(temRoleType)){
					user.setAuditStatus(0);
					user.setRoleType("游客");
					alumniUserMapper.updateByPrimaryKeySelective(user);
					result.put("state", "success");
					result.put("massege", "提交成功");
				} else {
					user.setAuditStatus(1);
					alumniUserMapper.updateByPrimaryKeySelective(user);
					updateUserFormId(user.getId(), formId);
					result.put("state", "success");
					result.put("massege", "提交成功");
				}
			} else {
				result.put("state", "failuren");
				result.put("massege", "角色不存在");
			}

		} else {
			result.put("state", "failuren");
			result.put("massege", "用户不存在");
		}
		return result;
	}

	/**
	 * 取消关注
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> cancelAlreadyFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
		if(afriUser != null) {
			alumniFriUserMapper.deleteByPrimaryKey(afriUser.getId());
			result.put("state", "success");
			result.put("massege", "取消成功");
		} else {
			result.put("state", "failuren");
			result.put("massege", "取消失败");
		}
		return result;
	}

	public Map<String, Object> selectUserConcernedByUserId(Integer id, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniFriUserMapper.selectUserByFKUserId(id);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("total", pageinfo.getTotal());
		resMap.put("items", list);
		return resMap;
	}

	public Map<String, Object> findMyOrganize(Integer id, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniUserMapper.selectMyOrganizeByUserId(id);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("total", pageinfo.getTotal());
		resMap.put("items", list);
		return resMap;
	}

	public List<AlumniUser> selectUserByUserName(String userName){
		return alumniUserMapper.selectUserByUserName(userName);
	}
	

	/**
	 * 更新用户的formId
	 * @param userId
	 * @param formId
	 */
	public void updateUserFormId(Integer userId, String formId) {
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String form_Id = user.getFormId();
			if(StringUtils.isNotBlank(form_Id)) {
				String[] formIds = form_Id.split(",");
				List<String>list = Arrays.asList(formIds);
				StringBuilder sb = new StringBuilder();
				for(int i = 0; i < list.size(); i++) {
					sb.append(list.get(i));
					if (sb.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
						sb.append(",");
					}
				}
				sb.append(formId);
				
				user.setFormId(sb.toString());
				alumniUserMapper.updateByPrimaryKeySelective(user);
			} else {
				StringBuilder sb = new StringBuilder();
				sb.append(formId);
				user.setFormId(sb.toString());
				alumniUserMapper.updateByPrimaryKeySelective(user);
			}
		}
	}

	/**
	 * 发送微信通知
	 * @param userId
	 * @param msgData
	 */
	public void sendWXMSG(Integer userId, MessageData msgData) {
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String form_Id = user.getFormId();
			if(StringUtils.isNotBlank(form_Id)) {
				String[] formIds = form_Id.split(",");
				List<String> listformId = new ArrayList<String>();
				for (String string : formIds) {
					listformId.add(string);
				}
				if(listformId.size() > 0) {
					String fromId = listformId.get(0);
					listformId.remove(0);
					if(listformId.size() > 0)
						user.setFormId(StringUtils.join(listformId, ","));
					else 
						user.setFormId("");
					
					alumniUserMapper.updateByPrimaryKeySelective(user);
					
					AccessToken accessToken = WeixinUtil.getAccessToken();
					if(accessToken != null) {
						String errmsg = WeixinUtil.sendWXMessage(accessToken.getToken(),user.getOpenId(), fromId, msgData);
						if(errmsg != null && !"ok".equals(errmsg)) {
							System.out.println(errmsg);
							sendWXMSG(userId, msgData);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 发送消息通知
	 * @param fkUserId 接收人id
	 * @param type 消息类型
	 * @param content 消息内容
	 * @param fromUserId 发送人id
	 */
	public void sendMessage(String fkUserId, String type, String content, String fromUserId) {
		AlumniUserMessage message = new AlumniUserMessage();
		message.setFkUserId(fkUserId);
		message.setMessageType(type);
		message.setContent(content);
		if(StringUtils.isNotBlank(fromUserId)) {
			message.setFromUserId(fromUserId);
		}
		message.setCreateTime(new Date());
		message.setIsRead(false);
		message.setIsDelete(false);
		alumniUserMessageMapper.insertSelective(message);
	}

    /**
     * 查询校友录数量（非游客）
     * @return
     */
    public int selectCountNotYK() {
        return (int)alumniUserMapper.selectCountNotYK();
    }

    public List<AlumniUser> allAlumniUser(AlumniUser alumniUser) {
    	return alumniUserMapper.selectAlumniUser(alumniUser);
    }

	/**
	 * 插入校友录驳回记录
	 * @param reason 驳回原因
	 * @param user 用户
	 */
	public void insertApproveHistory(Integer adminId , String reason, AlumniUser user){
		ApproveHistory approveHistory = new ApproveHistory();
		approveHistory.setUserId(user.getId());
		approveHistory.setCreateDate(new Date());
		approveHistory.setCreateBy(adminId+"");
		approveHistory.setComments(reason);
		String userInfo="用户信息:{";
		if(StringUtils.isNotBlank(user.getUserName())){
			userInfo += "用户名:'"+user.getUserName()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getGender())){
			userInfo += ", 性别:'"+user.getGender()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getEmail())){
			userInfo += ", 邮箱:'"+user.getEmail()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getPhone())){
			userInfo += ", 手机号:'"+user.getPhone()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getDegree())){
			userInfo += ", 学历:'"+user.getDegree()+ '\'';
		}
		if(user.getBeginDate() != null){
			userInfo += ", 入学时间:'"+user.getBeginDate()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getGuider())){
			userInfo += ", 导师:'"+user.getGuider()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getTemRoleType())){
			userInfo += ", 申请角色:'"+user.getTemRoleType()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getWorking())){
			userInfo += ", 工作单位:'"+user.getWorking()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getPosition())){
			userInfo += ", 职位:'"+user.getPosition()+ '\'';
		}
		if(StringUtils.isNotBlank(user.getPlace())){
			userInfo += ", 地址:'"+user.getPlace()+ '\'';
		}
		userInfo+="}";
		approveHistory.setUserInfo(userInfo);

		approveHistoryMapper.insertSelective(approveHistory);
	}

	/**
	 * 更新分数，赢的加分，输的扣分，0分的不再扣分
	 */
	public void recordScore(AlumniUser winner,boolean winnerIsRobot,AlumniUser loser,boolean loserIsRobot,Integer ScoreForEachGame){
		//赢的加分
		if(!winnerIsRobot) {//赢者非机器人
			winner.setPkScore(winner.getPkScore() + ScoreForEachGame);
			alumniUserMapper.updatePkScoreByOpenId(winner);
		}
		//输的扣分，有分数的，输的扣分，最多扣到0分
		if(!loserIsRobot) {//输者非机器人
			if (loser.getPkScore() > 0) {
				if (loser.getPkScore() < ScoreForEachGame) {//分数不足，扣到0分
					loser.setPkScore(0);
				} else {//正常扣分
					loser.setPkScore(loser.getPkScore() - ScoreForEachGame);
				}
				alumniUserMapper.updatePkScoreByOpenId(loser);
			}
		}
	}

	/**
	 * PK-好友排名、全球排名
	 * @param userId
	 * @param page
	 * @param size
	 * @return
	 */
	public Map<String, Object> ranking(boolean friendFlag,Integer userId, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<AlumniUser> list = null;
		if(friendFlag){//好友排名（仅展示关注的）
			 list = alumniUserMapper.selectFriendRanking(userId);
		}else{//世界排名
			 list = alumniUserMapper.selectWorldRanking(userId);
		}
		list.stream().forEach(item-> {
			item.setUserName( (item.getUserName()==null || "".equals(item.getUserName()))?"游客":item.getUserName());
			item.setPlace((item.getPlace() == null || "".equals(item.getPlace()) ) ? "未知" : item.getPlace().split(",")[1]);
			item.setLevel(item.getPkScore()==null?"暂无": CommonUtil.getLevel(item.getPkScore()));
		});
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("pageNum",pageinfo.getPageNum());
		resMap.put("pageSize", pageinfo.getPageSize());
		resMap.put("startRow", pageinfo.getStartRow());
		resMap.put("endRow", pageinfo.getEndRow());
		resMap.put("total", pageinfo.getTotal());
		resMap.put("pages", pageinfo.getPages());
		resMap.put("items", list);

		return resMap;
	}

	/**
	 * 根据用户名查询用户信息
	 * @param loginId
	 * @return
	 */
	public AlumniUser queryAlumniUserByLoginId(String loginId) {
		return alumniUserMapper.selectAlumniUserByLoginId(loginId);
	}
}
